# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper

  # Similar to ActionView::Helpers::FormHelper#form_for, but automatically sets
  # the :url and :html => :method options so that the same form can be easily
  # used for creating and editing a model controlled by a RESTful controller.
  # 
  # That is, if the given object is a new, unsaved record, the form's action URL 
  # will point to the 'create' action. If the given object is an existing, 
  # previously saved record, the form's action URL will point to the 'update' 
  # action.
  def restful_form_for(object_name, *args, &proc)
    object = instance_variable_get("@#{object_name}")
    options = args.last.is_a?(Hash) ? args.pop : {}
    
    if object.new_record?
      options[:url] = send("#{object_name.to_s.pluralize}_url")
      options[:html] = (options[:html] || {}).merge({:method => :post})
    else
      options[:url] = send("#{object_name}_url", object)
      options[:html] = (options[:html] || {}).merge({:method => :put})
    end
    
    form_for(object_name, *(args << options), &proc)
  end
  
  def error_messages_for(object_name, options = {})
    options = options.symbolize_keys # currently this is unused
    object = instance_variable_get("@#{object_name}")
    if object && !object.errors.empty?
      format_error(
        "Please correct the following errors in this #{object_name}:"+
        content_tag("ul",
          object.errors.full_messages.collect{|msg| content_tag("li", msg)}
        )
      )
    else
      ""
    end
  end
  
  def format_error(message)
    format_message(message, :error)
  end
  
  def format_notice(message)
    format_message(message, :notice)
  end
  
  def format_confirmation(message)
    format_message(message, :confirmation)
  end
  
  private
    def format_message(message, type)
      content_tag('div',
          message,
          'class' => "message #{type}"
        )
    end
  
end
